package com.sike.action;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.sike.model.MailSenderInfo;
import com.sike.service.BaseService;
import com.sike.util.ExcelUtil;
import com.sike.util.SimpleMailSender;

@Controller
@RequestMapping(value="sys")
public class SystemAction extends BaseAction {
	private HttpSession session;
	
	private BaseService service;
	
	@RequestMapping(value="/logout")
	public ModelAndView logout(HttpServletRequest request){
		session  = request.getSession();
		session.invalidate();
		ModelAndView view = new ModelAndView(); 
		view.setViewName("../../index");
		return view;
	}
	
	//密码重置
	@RequestMapping(value="/resetPass")
	public ModelAndView resetPass(HttpServletRequest request){
		Map<String,Object> map = this.getParameters();
		System.out.println(map);
		map.put("password", "111111");
		this.service.update("Member.update", map);
		ModelAndView view = new ModelAndView(); 
		view.setViewName("../../index");
		return view;
	}
	
	
	
	@RequestMapping(value="/validate")
	public ModelAndView validate(HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> m = this.getParameters();
		System.out.println(m);
		String name = request.getParameter("name")==null?"":request.getParameter("name").trim();
		String email = request.getParameter("email")==null?"":request.getParameter("email").trim();
		String idCard = request.getParameter("idCard")==null?"":request.getParameter("idCard").trim();
		List<String> list = new ArrayList<String>();
		Map<String,String> map = new HashMap<String,  String>();
		map.put("name", name);
		map.put("email", email);
		map.put("idCard", idCard);
		Map<String,Object> user = (HashMap<String, Object>)this.service.load("Member.load", map);
		System.out.println(user);
		
		PrintWriter out = null;
		JSONArray ja = JSONArray.fromObject(list);
		JSONObject jo = new JSONObject();
		try {
			response.setContentType("text/html;charset=utf-8");
			out = response.getWriter();
	
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(name.trim().equals("") || email.trim().equals("") || idCard.trim().equals("")){
			list.add("文本框内内容不能为空!");
		}
		if(user == null){
			list.add("根据输入信息，无此用户，请检查是否输入正确！");	
		}else{
			boolean b = this.sendMail(email,name);
			if(b){
				jo.put("success", "请到邮箱对个人密码进行重置!");
			}else{  
				list.add("发送邮件失败，请确认邮箱是否能有效接收发送邮件");
			}
		}
		jo.put("error", list);
		out.print(jo);
		out.close();
		return null;
	}
	
	
	
	
	
	
	
	
	@Resource(name="baseService")
	public void setService(BaseService service) {
		this.service = service;
	}

	public BaseService getService() {
		return service;
	}
	
	
	private boolean sendMail(String toAddress,String name){
		try{
			 MailSenderInfo mailInfo = new MailSenderInfo();    
			 mailInfo.setMailServerHost("smtp.163.com");    
			 mailInfo.setMailServerPort("25");    
			 mailInfo.setValidate(true);    
			 mailInfo.setUserName("sikejiaoyu@163.com");  
			 mailInfo.setPassword("sikejiaoyu123");//您的邮箱密码    
			 mailInfo.setFromAddress("sikejiaoyu@163.com");    
			 mailInfo.setToAddress(toAddress);    
			 mailInfo.setSubject("修改密码");    
			 mailInfo.setContent("<a href=http://localhost:8080/sike/sys/resetPass.action?name="+name+">请点击我进行密码重置，初始密码为111111,然后请到我的思科->个人中心->账号安全下对密码进行修改</a>");    
			  //这个类主要来发送邮件   
			 SimpleMailSender sms = new SimpleMailSender();   
			  //sms.sendTextMail(mailInfo);//发送文体格式    
			 SimpleMailSender.sendHtmlMail(mailInfo);//发送html格式   
			return true;
		}catch(Exception e){
			
			return false;
		}
	}
	
	
	@RequestMapping(value="/goApply")
	public ModelAndView goApply(HttpServletRequest request) throws Exception{
		session = request.getSession();
		Map<String, String> map = new HashMap<String, String>();
		map.put("name", (String)session.getAttribute("name"));
		Map<String, Object> user = (HashMap<String, Object>)this.service.load("Member.load", map);
		ModelAndView view = new ModelAndView();
		String applyName = request.getParameter("applyName");
		String type = request.getParameter("type");
		applyName = new String(applyName.getBytes("ISO-8859-1"),"utf-8");
		request.setAttribute("applyName", applyName);
		request.setAttribute("type", type);
		request.setAttribute("user", user);
		
		view.setViewName("user/apply");
		return view;
	}
	
	@RequestMapping(value="/applyTrate")
	public ModelAndView applyTrate(HttpServletRequest request,HttpServletResponse response) throws Exception{
		session  = request.getSession();
		Map<String, Object> map = this.getParameters();
		Map<String, Object> usermap = this.getParameters();
		usermap.put("name", session.getAttribute("name"));
		map.put("name", session.getAttribute("name"));
		Map<String, Object> user = (HashMap<String, Object>)this.service.load("Member.load", usermap);
		map.put("pic",user.get("pic"));
		map.put("ic", user.get("idCard"));
		map.put("email", user.get("email"));
		map.put("sikeUserId", user.get("id"));
		if(((String)map.get("type")).equals("0")){
			this.service.delete("Apply.delete", map);
			this.service.create("Apply.create", map);
		}
		if(((String)map.get("type")).equals("1")){
			this.service.delete("Train.delete", map);
			this.service.create("Train.create", map);	
		}
		String rootPath = request.getSession().getServletContext().getRealPath("/");
		ExcelUtil.excel(map,rootPath);
		ModelAndView view = new ModelAndView(); 
		view.setViewName("../../index");
		return view;
	}
	
	@RequestMapping(value="/download")
	public ModelAndView download(HttpServletRequest request,HttpServletResponse response) throws Exception{
		Map<String,Object> map = this.getParameters();
		session = request.getSession();
		String fileName = new String((session.getAttribute("name") + "-" + request.getParameter("content") + ".xls").getBytes("ISO-8859-1"),"utf-8");
		String rootPath = request.getSession().getServletContext().getRealPath("/");
		
		File file = new File(rootPath+"web/xlsfonder/"+fileName);
		response.setContentType("application/x-msdownload");
		response.setContentLength((int)file.length());
		response.setHeader("Content-Disposition","attachment;fileName="+fileName);
		
		response.setHeader("Content-Disposition","attachment;filename="+new String
				(fileName.getBytes("utf-8"),"iso-8859-1"));        

		
		FileInputStream fis=new FileInputStream(file);
		BufferedInputStream buff=new BufferedInputStream(fis);
		byte [] b=new byte[1024];//相当于我们的缓存
		long k=0;//该值用于计算当前实际下载了多少字节
		OutputStream myout=response.getOutputStream();
		while(k<file.length()){
			int j=buff.read(b,0,1024);
	        k+=j;
	        //将b中的数据写到客户端的内存
	        myout.write(b,0,j);
	    }
		 myout.flush();
		return null;
	}
	
	

	public HttpSession getSession() {
		return session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}
	
	
	
}
